<template>
	<div ref="refUnityMap" :class="$style['unity-map-container']" id="unityPlayer"></div>
</template>

<script setup name="unityMap">
import { ref, nextTick, onMounted, onBeforeUnmount } from 'vue'
import VueTypes from 'vue-types'
import useEventBus from "@/utils/event.bus"
import {
	fetchMapMarkersU3D
} from '@/api/map.services'

const props = defineProps({
	mapInfo: VueTypes.shape({
		map_file: String,
	}).loose.def({})
})

let eventBus = useEventBus(true)
let unity3d = null

const refUnityMap = ref(null)
const markers = ref([])

const initUnityMap = async () => {
	console.log('🚀[ ][ initUnityMap ][ props.mapInfo ] =>', props.mapInfo)
	await nextTick()

	const $wrapper = refUnityMap.value

	const config = {
		width: $wrapper.clientWidth, 
		height: $wrapper.clientHeight,
		params: { 
			enableDebugging: '0',
			disableContextMenu: true
		}
	}
	
	// 初始化 unity3dMap 实例
	unity3d = new UnityObject2(config)
	
	jQuery(function() {
		// 初始化插件并指定Unity内容路径
		unity3d.initPlugin(jQuery("#unityPlayer"), `${props.mapInfo.map_file}/DingYuan.unity3d`)
		
		// 监听进度
		unity3d.observeProgress(function(progress) {
			switch(progress.pluginStatus) {
				case "missing":
					// 插件未安装，提示安装
					console.log("Unity Web Player未安装，请安装插件")
					unity3d.installPlugin()
					break
				case "installed":
					// 插件已安装
					console.log("Unity Web Player已安装")
					break
				case "first":
					// 首帧渲染完成
					console.log("Unity内容加载完成")
					break
			}
		})
	})

	// unityMap 触发的报警，地图加载后可以通过这个函数添加报警
	window.raiseFakedAlarm = (moID, alarmSource, alarmTypeID) => {
		console.log('🚀[ ][ initUnityMap ][ moID, alarmSource, alarmTypeID ] =>', moID, alarmSource, alarmTypeID)
		// toDo 这里需要获取防区的对应数据
		const date = new Date()
		// const year = date.getFullYear()
		// const month = date.getMonth() + 1
		// const day = date.getDate()
		const hour = date.getHours()
		const minute = date.getMinutes()
		const second = date.getSeconds()
		const now_time = hour + ':' + minute + ':' + second
		const area_name = '防区1'
		const parm = `{"RaisedTime":"${now_time}","MeasObjID":"${moID}","MeasObjName":"${area_name}","AlarmSource":"${alarmSource}","AlarmSeverity":4,"AlarmID":99,"Cleared":false}`

		// 通知 unityMap 添加报警
		unity3d.getUnity().SendMessage('MainUI', 'AddAlarm', parm)
	}

	// unityMap 触发的 清除报警，地图加载后可以通过这个函数清除地图的报警
	window.clearAlarm = (alarmID) => {
		console.log('🚀[ ][ initUnityMap ][ alarmID ] =>', alarmID)
		const parm = `{"AlarmID":"${alarmID}","Cleared":true}`

		// 通知 unityMap 清除报警
		unity3d.getUnity().SendMessage('MainUI', 'RemoveAlarm', parm)
	}

	// unityMap 触发的 布防,moIDs防区编号
  window.enableMeasObj = (moIDs) => {
		// toDo 这里需要调用布防的接口
  }

  // unityMap 触发的 撤防,moIDs防区编号
	window.disableMeasObj = (moIDs) => {
		// toDo 这里需要调用撤防的接口
  }
}

const getMapMarker = async () => {
	const result = await fetchMapMarkersU3D(props.mapInfo.id)

	if (result.code == 1) {
		markers.value = result.data.data.filter(item => !!item.obj_id)
		console.log('🚀[ ][ getMapMarker ][ markers.value ] =>', markers.value)
	}
}

const handleAddAlarm = (event) => {
	console.log('🚀[ ][ handleAddAlarm ][ event ] =>', event)
	const postion = event.event_desc
	const moid = markers.value.find(item => item.name == event.device_name)?.obj_id

	if (!moid) {
		return
	}

	window.raiseFakedAlarm?.(moid, postion)
}

const handleRemoveAlarm = (event) => {
	console.log('🚀[ ][ handleRemoveAlarm ][ event ] =>', event)
	window.clearAlarm?.(event.event_id)
}

onMounted(() => {
	getMapMarker()
	initUnityMap()

	eventBus.register("eventReal", handleAddAlarm)
	eventBus.register("eventRealUpdate", handleAddAlarm)
	eventBus.register("guardAlarm", handleAddAlarm)
	eventBus.register("eventHandle", handleRemoveAlarm)
})

onBeforeUnmount(() => {
	eventBus.destroy()
	eventBus = null
	unity3d = null
})

</script>

<style lang="scss" module>
.unity-map-container {
	width: 100%; height: 100%;
}
</style>